<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">

<head>
  <meta charset="UTF-8">
  <title>多人在线聊天室</title>
  <link href="./favicon.ico" rel="shortcut icon" />
  <!-- <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
    <script src="axios.js"></script> -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
  <script src="https://cdn.socket.io/4.7.5/socket.io.min.js"
    integrity="sha384-2huaZvOR9iDzHqslqwpR87isEmrfxqyWOF7hr7BY6KG0+hVKLoEXMPUJw3ynWuhO"
    crossorigin="anonymous"></script>
  <style>
    * {
      padding: 0;
      margin: 0;
      list-style: none;
      box-sizing: border-box;
    }

    body {
      background: #1e1e1e;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh
    }

    .chat {
      background: #fff;
      width: 665px;
      height: 522px;
      display: flex;
      border-radius: 5px;
      box-shadow: -2px 2px 2px rgba(0, 0, 0, 0.5);
      overflow: hidden;
    }

    .users {
      width: 150px;
      border-right: 1px solid #ccc;
      line-height: 30px;
      overflow: auto;
      flex: 0 0 auto;
    }

    .users p {
      height: 50px;
      line-height: 50px;
      text-align: center;
      border-bottom: 1px solid #ccc;
    }

    .users li {
      padding: 0 10px;
      font-size: 12px;
      border-bottom: 1px solid #ccc;
      background: #f1f1f1;
    }

    .users li:nth-child(2n) {
      background: #fff;
    }

    .main {
      flex: 1 1 auto;
      background: #f1f1f1;
      display: flex;
      flex-direction: column;
    }

    .content-area {
      height: 400px;
      padding: 1em;
      overflow: auto;
      border-bottom: 1px solid #ccc;
      font-size: 14px;
      line-height: 1.5;
      flex: 0 0 auto;
      scroll-behavior: smooth;
    }

    .item {
      float: left;
      max-width: 70%;
      clear: both;
      margin-bottom: 1em;
    }

    .name {
      font-size: 12px;
      color: #666;
    }

    .date {
      color: #bbb;
      font-size: 12px;
      text-align: right;
    }

    .content {
      background: #fff;
      border-radius: 5px;
      padding: 10px;
      margin: 5px 0;
    }

    .mine.item {
      float: right;
    }

    .mine .content {
      background: #a9e97a;
    }

    .mine .name {
      text-align: right;
    }

    .mine .date {
      text-align: left;
    }

    .form {
      flex: 1 1 auto;
    }

    .form textarea {
      width: 100%;
      height: 100%;
      resize: none;
      border: none;
      outline: none;
      padding: 20px;
    }
  </style>
</head>

<body>

  <div class="chat" id="chat">
    <div class="users">
      <p>聊天室成员</p>
      <ul>
        <li v-for="user in users" :key="user">{{user}}</li>
      </ul>
    </div>
    <div class="main">
      <div class="content-area" id="info">
        <div class="item" :class="{ mine: me === item.name }" v-for="(item,index) in history" :key="index">
          <div class="name">{{item.name}}</div>
          <div class="content">{{item.content}}</div>
          <div class="date">{{formatDate(item.date)}}</div>
        </div>
      </div>
      <div class="form">
        <textarea v-model="value" @keydown.enter="handleEnter"></textarea>
      </div>
    </div>
  </div>

  <script type="module">
    import Hue from "../core/index.js";
    let socket = null
    window.test = new Hue({
      el: "chat",
      data: {
        me: 'hrc',
        value: '',
        users: [],
        history: []
      },
      // mounted() {
      //   this.$watch(
      //     'history',
      //     () => {
      //       const div = this.$refs.info;
      //       div.scroll(0, div.scrollHeight);
      //     },
      //     { immediate: true }
      //   );
      // },
      methods: {
        formatDate(date) {
          date = moment(date);
          return date.fromNow().replace(/\s/g, '');
        },
        handleEnter() {
          const dom = document.querySelector('textarea')
          dom.blur()
          const handleValue = this.value.trim();
          if (handleValue) {
            dom.value = ''
            this.value = ''
            const nowDate = Date.now()
            this.history.push({ name: this.me, content: handleValue, date: nowDate })
            socket.emit('$message', handleValue);
            //更新滚动条
            const infoDiv = document.getElementById('info')
            infoDiv.scroll(0, infoDiv.scrollHeight)
          }
        },
      },
      created() {
        // 设置语言环境
        moment.locale('zh-cn', {
          months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
          monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
          weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
          weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
          weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
          longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'YYYY-MM-DD',
            LL: 'YYYY年MM月DD日',
            LLL: 'YYYY年MM月DD日Ah点mm分',
            LLLL: 'YYYY年MM月DD日ddddAh点mm分',
            l: 'YYYY-M-D',
            ll: 'YYYY年M月D日',
            lll: 'YYYY年M月D日 HH:mm',
            llll: 'YYYY年M月D日dddd HH:mm'
          },
          meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
          meridiemHour: function (hour, meridiem) {
            if (hour === 12) {
              hour = 0;
            }
            if (meridiem === '凌晨' || meridiem === '早上' ||
              meridiem === '上午') {
              return hour;
            } else if (meridiem === '下午' || meridiem === '晚上') {
              return hour + 12;
            } else {
              // '中午'
              return hour >= 11 ? hour : hour + 12;
            }
          },
          meridiem: function (hour, minute, isLower) {
            const hm = hour * 100 + minute;
            if (hm < 600) {
              return '凌晨';
            } else if (hm < 900) {
              return '早上';
            } else if (hm < 1130) {
              return '上午';
            } else if (hm < 1230) {
              return '中午';
            } else if (hm < 1800) {
              return '下午';
            } else {
              return '晚上';
            }
          },
          calendar: {
            sameDay: '[今天]LT',
            nextDay: '[明天]LT',
            nextWeek: '[下]ddddLT',
            lastDay: '[昨天]LT',
            lastWeek: '[上]ddddLT',
            sameElse: 'L'
          },
          dayOfMonthOrdinalParse: /\d{1,2}(日|月|周)/,
          ordinal: function (number, period) {
            switch (period) {
              case 'd':
              case 'D':
              case 'DDD':
                return number + '日';
              case 'M':
                return number + '月';
              case 'w':
              case 'W':
                return number + '周';
              default:
                return number;
            }
          },
          relativeTime: {
            future: '%s内',
            past: '%s前',
            s: '几秒',
            ss: '%d秒',
            m: '1分钟',
            mm: '%d分钟',
            h: '1小时',
            hh: '%d小时',
            d: '1天',
            dd: '%d天',
            M: '1个月',
            MM: '%d个月',
            y: '1年',
            yy: '%d年'
          },
          week: {
            // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
            dow: 1, // Monday is the first day of the week.
            doy: 4  // The week that contains Jan 4th is the first week of the year.
          }
        })
        setTimeout(() => {
          //更新滚动条
          const infoDiv = document.getElementById('info')
          infoDiv.scroll(0, infoDiv.scrollHeight)
        }, 200)
        socket = io('ws://localhost:9528') //连接，握手
        socket.on('$updateUser', (users) => {
          this.users = users
        })
        socket.on('$name', (name) => {
          this.me = name
        })
        socket.on('$history', (history) => {
          this.history = history
        })
        socket.on('$message', (message) => {
          this.history.push(message)
          //更新滚动条
          const infoDiv = document.getElementById('info')
          infoDiv.scroll(0, infoDiv.scrollHeight)
        })
      },
      // beforeDestroy() {
      //   this.socket.isconnect() //关闭连接
      // }
    });
  </script>
</body>

</html>